package com.lx.vcode.web;


import com.lx.util.Utils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


@Component
public class VcodeInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler) throws Exception {

        // 用户输入的验证码
        String rcode = request.getParameter("vcode");
        // 会话中保存的验证码
        String vcode = (String) request.getSession().getAttribute("vcode");
        Long time = (Long) request.getSession().getAttribute("vcode-timeout");

        if(vcode == null){
            Utils.WriteResult(0, "请先获取验证码", null, response);
            return false;
//            throw new VcodeException("请先获取验证码");
        }
        if(time < System.currentTimeMillis()){
            request.getSession().removeAttribute("vcode");
            request.getSession().removeAttribute("vcode-timeout");
            Utils.WriteResult(0, "验证码过期", null, response);
            return false;
        }
        if(vcode == null){

            Utils.WriteResult(0, "请先输入验证码", null, response);
            return false;

        }
        if(!vcode.equalsIgnoreCase(rcode)){

            Utils.WriteResult(0, "输入验证码错误", null, response);
            return false;
//            throw new VcodeException("输入验证码错误");
        }


        // 移除会话中的验证码
        request.getSession().removeAttribute("vcode");
        request.getSession().removeAttribute("vcode-timeout");
        // 放行请求到达目标资源(一般指控制器)
        return true;

    }
}
